// 参数说明：图片地址（本地或者线上url）、处理后返回的base64内容、指定图片类型

export function imgToBase64(urls){
  let ps = urls.map(res => {
    return _imgToBase64(res.url,res.type);
  });
  return Promise.all(ps);
}

function _imgToBase64(url, outputFormat) {
  return new Promise(resolve => {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function() {
      var width = img.width;
      var height = img.height;
      
      // 压缩比例 -- 可以自己修改参数。500px宽度以下原尺寸，大于500px比例处理
      //var bili = Math.round(width / 500) || 1;
      var bili = 1;
      var rate = 1 / bili;
      canvas.width = width * rate;
      canvas.height = height * rate;
      ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
      var dataURL = canvas.toDataURL(outputFormat || 'image/png');
      // 去除标头 -- 传递给后台时一般去除头部
      // var reg = new RegExp('^data:image/[^;]+;base64,');
      // dataURL = dataURL.replace(reg, '');
      canvas = null;
      resolve(dataURL);
    }
    img.src = url;
  })
};


//wx.getFileSystemManager().readFile() 本地照片或拍照这种可以转化解析wxfile://xxxx
export function imgToBase64WxminiLocal(filePath){
  return new Promise(resolve => {
    wx.getFileSystemManager().readFile({
      filePath, //要读取的文件的路径 (本地路径)
      encoding: "base64", //指定读取文件的字符编码，如果不传 encoding，则以 ArrayBuffer 格式读取文件的二进制内容
      success(res) {
        resolve(res.data);
      }
    })
  })
}

//wx.request() 这种方式适合网络https路径图片，但无法解析wxfile://xxxx导致转化报错
export function imgToBase64WxminiRomote(url){
  return new Promise((resolve, reject) => { // promise 解决异步问题
    wx.request({
      url,
      responseType: 'arraybuffer', //最关键的参数，设置返回的数据格式为arraybuffer
      success: (res) => {
        var base64 = wx.arrayBufferToBase64(res.data);
        base64 = 'data:image/jpeg;base64,' + base64;
        resolve(base64);
      },
      fail: (res) => {
        reject(false);
      }
    })
  })
}

//<canvas id="myCanvas" type="2d" hidden="true"></canvas>
//使用canvas 获取图片base64
export function imgToBase64WxminiCanvas(tempFilePath){
//使用canvas 获取图片base64
  return new Promise(resolve => {
    wx.getImageInfo({
      src: tempFilePath,
      success(res){
        resolve(res);
      }
    })
  }).then(res => {
    const { width,height } = res;
    const base64 = new Promise(resolve => {
      const query = wx.createSelectorQuery();
      query.select("#myCanvas").fields({
        node: true, // 获取 node
      }).exec(res => {

        let {
          node: canvas
        } = res[0];

        let ctx = canvas.getContext('2d');
        let image = canvas.createImage();

        image.src = tempFilePath;
        image.onload = () => {
          ctx.drawImage(image, 0, 0, width, height);
          resolve(canvas.toDataURL())
        }
      });
    });
    return base64;
  })
}
